/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-04-09 12:34:34
 * @LastEditors: shentong
 * @LastEditTime: 2022-02-25 21:54:16
 */
// eslint-disable-next-line @typescript-eslint/no-use-before-define
import React, { useEffect, useState, useMemo, useCallback } from "react";
import Taro, { useDidShow, useRouter } from '@tarojs/taro'

import { connect } from 'react-redux'

 import { View } from "@tarojs/components";

 import { showToast , userAPIAuthSeting, showFloorSchoolList, getStoregeByKey } from '@/utils/index'

 import { AtActionSheet, AtActionSheetItem } from "taro-ui"

import { IsaveAddressRequst, saveAddress, saveEditAddress, getFloor } from '@/api/user'

 import styles from './index.module.scss'

 const AddAddress = (props) => {
  const { curAddress, curSchool, dispatch } = props

   const [userName, setUserName] = useState<string>('');
   const [gender, setGender] = useState<number | string>(0);
   const [cellPhone, setCellPhone] = useState<string>('');
   const [address, setAddress] = useState<string>('');
   const [addressId, setAddressId] = useState<string>('');
   const [lon, setLon] = useState<string>('');
   const [lat, setLat] = useState<string>('');
   const [detailAdd, setDetailAdd] = useState<string>('');
   const [deliveryFloor, setDeliveryFloor] = useState<string | number>('');
   const [floorName, setFloorName] = useState<string>('');

   const [isOpendSheet, setIsOpendSheet] = useState<boolean>(false);
   const [isOpendSheetFloor, setIsOpendSheetFloor] = useState<boolean>(false);
   const [showFloorSelect, setShowFloorSelect] = useState<boolean>(false);
   const [floorList, setFloorList] = useState<Array<any>>([]);

   const chooseLocation = requirePlugin('chooseLocation');

   const routerParams = useRouter().params;

   const genderList = useMemo(() => {
     return [{gender: 0, text: '先生'}, {gender: 1, text: '女士'}]
   }, [])

   // 输入手机号
   const userNameChange = (e) => {
    setUserName(e.detail)
   }

    const sheetItemClick = (item) => {
      setGender(item.gender)
      setIsOpendSheet(false)
    }

    const sheetFloorItemClick = (item) => {
      setDeliveryFloor(item.code)
      setFloorName(item.desc)
      setIsOpendSheetFloor(false)
    }

   const bindClickAdress = () => {
    Taro.navigateTo({url: `/pages/schoolList/index?isFromAddress=1`})
    // const key = 'JHLBZ-5MQ6U-LBSVL-BBNL4-KPK5S-S4B36'; //使用在腾讯位置服务申请的key
    // const referer = '校园颂'; //调用插件的app的名称

    // userAPIAuthSeting('scope.userLocation',{},() => {
    //   Taro.getLocation({
    //     type: 'gcj02', //返回可以用于 Taro.openLocation的经纬度
    //     success: function (res) {
    //       const location = JSON.stringify({
    //         latitude: res.latitude,
    //         longitude: res.longitude
    //       });
    //       Taro.navigateTo({
    //         url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`
    //       });
    //     }
    //   })
    // })
   }

   const newAddress = (item) => {
    dispatch({ type: 'NEWADDRESS', payload: {
      address: item.address || '',
      cellPhone: item.cellPhone || '',
      detailAdd: item.detailAdd || '',
      gender: item.gender,
      userName: item.userName || '',
      lat: item.lat || '',
      lon: item.lon || '',
      addressId: item.addressId || '',
      deliveryFloor: item.deliveryFloor || ''
    }})
  }

   const saveHandle = () => {
     if (showFloorSelect && !deliveryFloor) {
       return showToast('请选择楼层~')
     }
    Taro.showLoading({ title: "正在保存...", mask: true })
    const params: IsaveAddressRequst = {
      userName,
      cellPhone,
      detailAdd,
      address,
      addressId,
      lon,
      lat,
      gender,
      deliveryFloor
    }
    const reqApi = addressId && routerParams.isEdit === '1'
      ? saveEditAddress
      : saveAddress

    reqApi(params).then((res) => {
      console.log('save-res', res)
      // Taro.hideLoading();
      showToast('保存成功', {
        complete () {
          // 更新redux中的地址信息
          newAddress(Object.assign(params, {
            addressId: res.data
          }))
          dispatch({ type: 'CLEAR_CUR_SCHOOL'})
          Taro.navigateBack()
        }
      })
    })
   }

  //  useEffect(() => {
  //   console.log('curSchool----', curSchool)
  //  }, [curSchool])

  useDidShow(() => {
    // const location = chooseLocation.getLocation()
    // const reduceCurSchool = curSchool
    // console.log('curSchool----', curSchool)
    if (curSchool && curSchool.schoolSId) {
      const { lat , lon, schoolName} = curSchool
      setAddress(schoolName)
      setLat(lat)
      setLon(lon)
    } else if (routerParams.isEdit === '1') {
      setUserName(curAddress.userName)
      setCellPhone(curAddress.cellPhone)
      setGender(curAddress.gender)
      setAddress(curAddress.address)
      setDetailAdd(curAddress.detailAdd)
      setAddressId(curAddress.addressId)
      setLat(curAddress.lat)
      setLon(curAddress.lon)
      setDeliveryFloor(curAddress.deliveryFloor)
    }
  })

  const getfloorList = () => {
    judgeSchool().then(userInfo => {
      const { schoolSId = '' } = userInfo
      setShowFloorSelect(schoolSId && showFloorSchoolList.includes(schoolSId))
    })
    getFloor().then(res => {
      if (res.data && Array.isArray(res.data)){
        setFloorList([...res.data])
        if (routerParams.isEdit === '1') {
          const curFloor = res.data.find(item => item.code === Number(curAddress.deliveryFloor)) || {}
          setFloorName(curFloor.desc)
        }
      }
    })
  }

   // 判断当前学校是否现显示'选择楼层’
   const judgeSchool = useCallback(async () => {
    // 获取用户信息
    const userInfo = await getStoregeByKey('userInfo')

    return userInfo

  }, [])

  const sheetClose = (type) => {
    if (type === 'gender') {
      setIsOpendSheet(false)
    } else {
      setIsOpendSheetFloor(false)
    }
  }

   useEffect(() => {
    getfloorList()
   }, []);

   return (
     <View className={styles.addAddress}>
        <View className={styles.cellList}>
          <van-cell-group>
            <View onClick={bindClickAdress}>
              <van-field
                value={address}
                required
                readonly
                label='收货地址'
                placeholder='请选择地址'
                icon='arrow'
                border
              />
            </View>

            <van-cell-group>
              <van-field
                value={detailAdd}
                required
                label='门牌号'
                type='textarea'
                placeholder='请填写详细地址'
                autosize
                border
                onChange={(e) => setDetailAdd(e.detail)}
              />
            </van-cell-group>

            <van-field
              value={userName}
              required
              clearable
              label='联系人'
              placeholder='请填写联系人'
              border
              onChange={userNameChange}
            />

            <van-field
              value={cellPhone}
              label='手机号'
              placeholder='请填写手机号'
              required
              border={false}
              onChange={(e) => setCellPhone(e.detail)}
            />
          </van-cell-group>

          <van-cell
            required
            isLink
            onClick={() => setIsOpendSheet(true)}
            title='性别'
            value={Number(gender) === 0 ? '先生' : '女士'}
            titleStyle='color: #646566;'
          />

{
          floorList.length && showFloorSelect ? (
            <van-cell
              required
              isLink
              onClick={() => setIsOpendSheetFloor(true)}
              title='收货楼层'
              value={floorName}
              titleStyle='color: #646566;'
            />
          ) : null
        }


        </View>
        <View className={styles.saveBtn} onClick={saveHandle}>
          保存地址
        </View>
        <AtActionSheet isOpened={isOpendSheet} onCancel={() => sheetClose('gender')} onClose={() => sheetClose('gender')} cancelText='取消' title='请选择性别'>
          {
            genderList.map((item, index) => {
              return <AtActionSheetItem key={index} onClick={() => sheetItemClick(item)}>{item.text}</AtActionSheetItem>
            })
          }
        </AtActionSheet>

        <AtActionSheet isOpened={isOpendSheetFloor} onCancel={() => sheetClose('floor')} onClose={() => sheetClose('floor')} cancelText='取消' title='请选择楼层'>
              {
                floorList.map((item, index) => {
                  return <AtActionSheetItem key={index} onClick={() => sheetFloorItemClick(item)}>{item.desc}{`（配送费增加${item.amount}元）`}</AtActionSheetItem>
                })
              }
        </AtActionSheet>
     </View>
   );
 }

 export default connect(({ curAddress, curSchool }) => ({
  curAddress,
  curSchool
}),dispatch => ({
  dispatch
}))(AddAddress)
